/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.maixiami;

import com.taobao.api.domain.ItemCat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author qye
 */
public class ItemCategories<T extends ItemCat> {
    Map<Long, T> itemCatsMap = new HashMap<Long, T>();
    Map<Long, List<T> > itemCatsTree = new HashMap<Long, List<T> >();
    
    public ItemCategories(List<T> itemCats) {
        for(T cat : itemCats) {
            itemCatsMap.put(cat.getCid(), cat);
        }
        
        itemCatsTree.put(0L, new ArrayList<T>());
        for(T cat : itemCats) {
            List<T> cats = itemCatsTree.get(cat.getParentCid());
            if(cats == null) {
                cats = new ArrayList<T>();
                itemCatsTree.put(cat.getParentCid(), cats);
            }
            
            cats.add(cat);
        }
    }
    
    public T getItemCat(Long id) {
        return itemCatsMap.get(id);
    }
    
    public T getParent(Long id) {
        T cat = itemCatsMap.get(id);
        if(cat == null) {
            System.out.println("not exist:\t" + id);
            return null;
        }
        return getItemCat(cat.getParentCid());
    }
    
    public Long getSecondAncestor(Long id) {
        assert id.longValue() != 0L;
        assert itemCatsMap.get(id).getParentCid().longValue() != 0L;
        while(true) {
            ItemCat itemCat = itemCatsMap.get(id);
            if(itemCat == null)
                return id;
            Long parent = itemCat.getParentCid();
            
            itemCat = itemCatsMap.get(parent);
            if(itemCat == null)
                return id;
            Long grandparent = itemCat.getParentCid();
            if(grandparent.longValue() == 0L)
                return id;
            else
                id = parent;
        }
    }
    
    public List<T> getChildren(Long id) {
        return itemCatsTree.get(id);
    }
}
